﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Utilities;

namespace StockCommon.data.TradeDetail
{
    public class TradeInstManager
    {
        protected static Dictionary<string, Inst> insts = null;
        public static void preload()
        {
            StockDataClassesDataContext context = LinqAgent.getContext();
            insts= (from i in context.Insts orderby i.InstCode select i).ToDictionary(i => i.InstCode);
        }
        public static int removeInst(String code)
        {
            code = code.Trim();
            if (insts == null)
                preload();
            if (insts.ContainsKey(code) == false)
                return 0;

            StockDataClassesDataContext context = LinqAgent.getContext();
            String sql=String.Format("delete from insts where InstCode='{0}'", code);
            int i=context.ExecuteCommand(sql);
            insts.Remove(code);
            return i;
        }
        public static bool getInstId(String code, out Guid result)
        {
            code = code.Trim();
            if (insts == null)
                preload();
            if (insts.ContainsKey(code))
            {
                result = insts[code].InstId;
                return true;
            }
            result = Guid.Empty;
            return false;
        }
        /******************************************************************************
         * 
         * 
         * 
         ******************************************************************************/
        public static Guid registerInst(String code, String name)
        {
            if (insts == null)
                preload();
            code = code.Trim();
            if (String.IsNullOrWhiteSpace(code))
                return Guid.Empty;

            if (insts.ContainsKey(code))
                return insts[code].InstId;

            Inst record = new Inst();
            record.InstId = NewGUID.create("inst");
            record.InstCode = code;
            record.InstName = name.Trim();
            StockDataClassesDataContext context = LinqAgent.getContext();
            context.Insts.InsertOnSubmit(record);
            context.SubmitChanges();
            insts.Add(record.InstCode, record);
            return record.InstId;
        }
        /******************************************************************************
         * 
         * 
         * 
         ******************************************************************************/




    }
}
